package com.ndood.authenticate.core.social.mini.connect;

import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

import com.ndood.authenticate.core.social.mini.api.MiniProgram;

/**
 * 微信连接工厂
 */
public class MiniOauth2ConnectionFactory extends OAuth2ConnectionFactory<MiniProgram> {
	
	public MiniOauth2ConnectionFactory(String providerId, String appId, String appSecret) {
		super(providerId, new MiniOauth2ServiceProvider(appId, appSecret), new MiniApiAdapter());
	}
	
	/**
	 * 由于微信的openId是和accessToken一起返回的，所以在这里直接根据accessToken设置providerUserId即可，不用像QQ那样通过QQAdapter来获取
	 */
	@Override
	protected String extractProviderUserId(AccessGrant accessGrant) {
		if(accessGrant instanceof MiniAccessToken) {
			return ((MiniAccessToken)accessGrant).getOpenId();
		}
		return null;
	}
		
	public Connection<MiniProgram> createConnection(AccessGrant accessGrant) {
		return new OAuth2Connection<MiniProgram>(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
				accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getOAuth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
	}

	public Connection<MiniProgram> createConnection(ConnectionData data) {
		return new OAuth2Connection<MiniProgram>(data, getOAuth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
	}
	
	private ApiAdapter<MiniProgram> getApiAdapter(String providerUserId) {
		return new MiniApiAdapter();
	}
	
	private OAuth2ServiceProvider<MiniProgram> getOAuth2ServiceProvider() {
		return (OAuth2ServiceProvider<MiniProgram>) getServiceProvider();
	}
}